package com.qunar.support.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.qunar.support.util.DBHelper;
import com.qunar.support.util.TimeHelper;

public class LoginLogDao {
	private Connection con;

	private static final int LOGKEEPDATE = 30;
	/**
	 * 登陆日志insert！
	 * @param uid
	 * @param ip
	 */
	public void logLogin(int uid, String ip) {
		try {
			con = DBHelper.getConnection();
			String insert = "insert into loginlog(user_id,ip,login_time) values(?,?,?)";
			PreparedStatement pstmt = con.prepareStatement(insert);
			pstmt.setInt(1, uid);
			pstmt.setString(2, ip);
			pstmt.setString(3, TimeHelper.getLogTime());
			pstmt.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 分页获取指定用户的登陆日志
	 * @param uid
	 * @param startIndex
	 * @return
	 * @author ziqiang.deng
	 */
	public List<JSONObject> getLoginLogByPage(int uid,int startIndex){
		String sql = "SELECT ip,time from loginlog WHERE user_id = ? limit ?,10;";
		try {
			con = DBHelper.getConnection();
			PreparedStatement pstmt=con.prepareStatement(sql);
			pstmt.setInt(1, uid);
			pstmt.setInt(2, startIndex);
			ResultSet rs = pstmt.executeQuery();
			List<JSONObject> r = new ArrayList<JSONObject>();
			while( rs.next() ){//一条记录对应一个JSONObject
				JSONObject json = new JSONObject();
				json.put("ip", rs.getString("ip") );
				json.put("time", rs.getString("login_time") );
				r.add(json);
			}
			return r;
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	/**
	 * 清除30天前的登录日志
	 * @author ziqiang.deng
	 */
	public void clearLoginLog(){
		String sql = "DELETE FROM loginlog WHERE DATEDIFF(now(), loginlog.login_time) > ?;";
		this.con = DBHelper.getConnection();
		try {
			PreparedStatement pstmt=con.prepareStatement(sql);
			pstmt.setInt(1, LOGKEEPDATE);
			pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return ;
	}
	
	
	
}
